﻿using CoreLims.Models.CoreLims;
using IronPython.Runtime;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Scripting.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace CoreLims.Controllers
{
    [Authorize]
    public class SAMPLEController : Controller
    {
        private readonly CoreLimsContext dbContext;
             
        public SAMPLEController(CoreLimsContext context)
        {
            dbContext = context;
        }
        private class HtmlConvert
        {
            /// <summary>
            /// HTML转换为PDF
            /// </summary>
            /// <param name="htmlPath">可以是本地路径，也可以是网络地址</param>
            /// <param name="savePath">PDF文件保存的路径</param>
            /// <returns></returns>
            public bool HtmlConvertToPdf(string htmlPath, string savePath)
            {
                bool flag = false;
                //验证保存路径是否正确
                CheckFilePath(savePath);

                //这个路径为程序集的目录，因为我把应用程序 wkhtmltopdf.exe 放在了程序集同一个目录下
                //string exePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "wkhtmltopdf.exe";
                string exePath = @"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe";
                if (!System.IO.File.Exists(exePath))
                {
                    throw new Exception("没有找到wkhtmltopdf.exe应用程序");
                }

                try
                {
                    ProcessStartInfo processStartInfo = new ProcessStartInfo();
                    processStartInfo.FileName = exePath;
                    processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
                    processStartInfo.UseShellExecute = false;
                    processStartInfo.CreateNoWindow = true;
                    processStartInfo.RedirectStandardInput = true;
                    processStartInfo.RedirectStandardOutput = true;
                    processStartInfo.RedirectStandardError = true;
                    processStartInfo.Arguments = GetArguments(htmlPath, savePath);

                    Process process = new Process();
                    process.StartInfo = processStartInfo;
                    process.Start();
                    process.WaitForExit();

                    ///用于查看是否返回错误信息
                    //StreamReader srone = process.StandardError;
                    //StreamReader srtwo = process.StandardOutput;
                    //string ss1 = srone.ReadToEnd();
                    //string ss2 = srtwo.ReadToEnd();
                    //srone.Close();
                    //srone.Dispose();
                    //srtwo.Close();
                    //srtwo.Dispose();

                    process.Close();
                    process.Dispose();
                    flag = true;
                }
                catch
                {
                    flag = false;
                }
                return flag;
            }

            /// <summary>
            /// 获取命令行参数
            /// </summary>
            /// <param name="htmlPath">html路径，可以是本地路径，也可以是网络地址</param>
            /// <param name="savePath">PDF文件保存的路径</param>
            /// <returns></returns>
            private string GetArguments(string htmlPath, string savePath)
            {
                if (string.IsNullOrEmpty(htmlPath))
                {
                    throw new Exception("HTML本地路径或网络地址不能为空.");
                }

                if (string.IsNullOrEmpty(savePath))
                {
                    throw new Exception("PDF文档保存的路径不能为空.");
                }

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(" --page-height 200 ");        //页面高度100mm
                stringBuilder.Append(" --page-width 250 ");         //页面宽度100mm
                stringBuilder.Append(" --header-center 我是页眉（www.51baidu.com.cn） ");  //设置居中显示页眉
                stringBuilder.Append(" --header-line ");         //页眉和内容之间显示一条直线
                stringBuilder.Append(" --footer-center \"Page [page] of [topage]\" ");    //设置居中显示页脚
                stringBuilder.Append(" --footer-line ");       //页脚和内容之间显示一条直线
                stringBuilder.Append(" " + htmlPath + " ");       //本地 HTML 的文件路径或网页 HTML 的URL地址
                stringBuilder.Append(" " + savePath + " ");       //生成的 PDF 文档的保存路径
                return stringBuilder.ToString();
            }

            /// <summary>
            /// 验证保存路径
            /// </summary>
            /// <param name="savePath">需要验证的路径</param>
            private void CheckFilePath(string savePath)
            {
                string ext = string.Empty;
                string path = string.Empty;
                string fileName = string.Empty;

                ext = Path.GetExtension(savePath);
                if (string.IsNullOrEmpty(ext) || ext.ToLower() != ".pdf")
                {
                    throw new Exception("此方法用于生成PDF文件.");
                }

                fileName = Path.GetFileName(savePath);
                if (string.IsNullOrEmpty(fileName))
                {
                    throw new Exception("文件名为空.");
                }

                try
                {
                    path = savePath.Substring(0, savePath.IndexOf(fileName));
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                }
                catch
                {
                    throw new Exception("文件路径不存在.");
                }
            }

        }

        #region SampleDomain

        [HttpPost]
        public string HtmltoPdf(string url)
        {
            string htmlUrl = url;
            HtmlConvert convert = new HtmlConvert();
            convert.HtmlConvertToPdf(htmlUrl, AppDomain.CurrentDomain.BaseDirectory.ToString() + @"File\htmlUrl.pdf");

            return "PDF文件生成成功！";
        }

        #endregion

        #region 分析项相关
        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult Analyte()
        {
            return View(SAMPLE.Analyte.getAnalyteList(dbContext).Distinct(new SAMPLE.AnalyteClassificationCompare()));
        }

        [HttpPost]
        public ViewResult AddAnalyte(string Id, string ModalID)
        {
            ViewData["AnalyteId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View(SAMPLE.Analyte.getAnalyteList(dbContext).Distinct(new SAMPLE.AnalyteClassificationCompare()));
        }

        [HttpPost]
        public JsonResult GetAnalyte(string Id)
        {
            var analyte = SAMPLE.Analyte.getAnalyte(dbContext, Id);
            return Json(analyte);
        }

        [HttpPost]
        public JsonResult GetAnalyteClassification()
        {
            var classification = dbContext.Analyte.ToList().Distinct(new SAMPLE.AnalyteClassificationCompare()).Select(s => new { s.Classification });
            return Json(classification);
        }

        [HttpPost]
        public JsonResult GetAnalyteListByClassification(string Classification)
        {
            var list = SAMPLE.Analyte.getAnalyteListByClassification(dbContext, Classification);
            return Json(list);
        }

        [HttpPost]
        public RedirectToActionResult GetUnitType()
        {
            return RedirectToAction(actionName: "GetUnitType", controllerName: "Common");
        }

        [HttpPost]
        public RedirectToActionResult AddUnit()
        {
            return RedirectToAction(actionName: "AddUnit", controllerName: "Common");
        }

        [HttpPost]
        public RedirectToActionResult postAddUnit(string jsonUnit)
        {
            return RedirectToAction(actionName: "postAddUnit", controllerName: "Common", new { jsonUnit = jsonUnit });
        }

        [HttpPost]
        public string postAddAnalyte(string jsonStr)
        {
            SampleAnalyte analyte = JsonConvert.DeserializeObject<SampleAnalyte>(jsonStr);  //反序列化，字符串转换为类
            var st = analyte.AddAnalyte(dbContext);
            return st;
        }

        [HttpPost]
        public string postUpdateAnalyte(string jsonStr)
        {
            SampleAnalyte analyte = JsonConvert.DeserializeObject<SampleAnalyte>(jsonStr);  //反序列化，字符串转换为类
            var st = analyte.UpdateAnalyte(dbContext);
            return st;
        }

        [HttpPost]
        public string UpdateAnalyteEqtype(string Id, string EqType)
        {
            SampleAnalyte analyte = SAMPLE.Analyte.getAnalyte(dbContext, Id);
            analyte.EqType = EqType;
            var st = analyte.UpdateAnalyte(dbContext);
            return st;
        }

        [HttpPost]
        public string postUpdateAnalyteByIDD(string Id, string DefaultSpecId, string DefaultSpecName)
        {
            var st = SAMPLE.Analyte.UpdateAnalyte(dbContext, Id, DefaultSpecId, DefaultSpecName);
            return st;
        }

        [HttpPost]
        public string postDeleteAnalyte(string Id)
        {
            return SAMPLE.Analyte.DeleteAnalyte(dbContext, Id);
        }

        [HttpPost]
        public ViewResult SelectEquipmentType(string SampleAnalyteId, string ModalID)
        {
            ViewData["SampleAnalyteId"] = SampleAnalyteId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult UpdateAssist(string Id, string Assist)
        {
            var st = SAMPLE.Analyte.UpdateAssist(dbContext, Id, Assist);
            return Json(st);
        }

        [HttpPost]
        public JsonResult UpdateCMA(string Id, string CMA)
        {
            var st = SAMPLE.Analyte.UpdateCMA(dbContext, Id, CMA);
            return Json(st);
        }

        [HttpPost]
        public JsonResult UpdateCNAS(string Id, string CNAS)
        {
            var st = SAMPLE.Analyte.UpdateCNAS(dbContext, Id, CNAS);
            return Json(st);
        }

        //[HttpPost]
        //public JsonResult GetEquipmentTypeList(string SampleAnalyteId) //关联设备类型
        //{
        //    var list = Eq.getEquipmentList(dbContext).Distinct(new Eq.EquipmentTypeCompare())
        //        .Select(x => x.Type);

        //    var useList = SAMPLE.Analyte.getAnalyte(dbContext, SampleAnalyteId).EquipmentTypeList;
        //    var utl = new List<UseTypeList>();

        //    foreach (var item in list)
        //    {
        //        utl.Add(new UseTypeList { Type = item, Use = useList == null ? false : useList.Contains(item) });
        //    }

        //    return Json(utl);
        //}

        //[HttpPost]
        //public string postUpdateEquipmentTypeList(string SampleAnalyteId, string EquipmentTypeList)
        //{
        //    var st = SAMPLE.Analyte.UpdateAnalyteEquipmentTypeList(dbContext, SampleAnalyteId, EquipmentTypeList);
        //    return st;
        //}

        #endregion

        #region 指标相关
        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult Spec() => View();

        [HttpPost]
        public ViewResult SelectSpec(string Id)
        {
            ViewData["AnalyteId"] = Id;
            return View();
        }

        [HttpPost]
        public ViewResult AddSpec(string Id, string ModalID)
        {
            ViewData["SpecId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult AddSpecRelationAnalyte(string Relation, string Id, string ModalID)
        {
            ViewData["Relation"] = Relation;
            ViewData["SpecId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult SpecAcceptanceRules(string Id, string ModalID)
        {
            ViewData["SpecId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetSpec(string Id)
        {
            var spec = SAMPLE.Spec.getSpec(dbContext, Id);
            return Json(spec);
        }

        [HttpPost]
        public JsonResult GetSpecFirstGroup()
        {
            var first = SAMPLE.Spec.getSpecList(dbContext).Distinct(new SAMPLE.SpecFirstGroupCompare()).Select(s => new { s.FirstGroup });
            return Json(first);
        }

        [HttpPost]
        public JsonResult GetSpecSecondGroup(string FirstGroup)
        {
            var second = SAMPLE.Spec.getSpecListByFirstGroup(dbContext, FirstGroup)
                .Distinct(new SAMPLE.SpecSecondGroupCompare())
                .Select(s => new { s.SecondGroup });

            return Json(second);
        }

        [HttpPost]
        public JsonResult GetSpecListByFirstGroup(string FirstGroup)
        {
            var first = SAMPLE.Spec.getSpecListByFirstGroup(dbContext, FirstGroup).Select(s => new { s.Id, s.Code, s.Name, s.Description });
            return Json(first);
        }

        [HttpPost]
        public JsonResult GetSpecListFirstAndBySecond(string FirstGroup, string SecondGroup)
        {
            var first = SAMPLE.Spec.getSpecListByFirstAndSecond(dbContext, FirstGroup, SecondGroup).Select(s => new { s.Id, s.Code, s.Name, s.Description });
            return Json(first);
        }

        [HttpPost]
        public JsonResult GetSpecListByFirstAndSecondAllField(string FirstGroup, string SecondGroup, string limit, string offset)
        {
            var first = SAMPLE.Spec.getSpecListByFirstAndSecond(dbContext, FirstGroup, SecondGroup)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.Spec.getSpecListByFirstAndSecond(dbContext, FirstGroup, SecondGroup).Count;
            res.rows = first;

            return Json(res);
        }

        [HttpPost]
        public JsonResult UpdateSpecEnable(string Id, string Enable)
        {
            var st = SAMPLE.Spec.UpdateSpecEnable(dbContext, Id, Enable);
            return Json(st);
        }

        [HttpPost]
        public string GetSpecAcceptanceRules(string Id)
        {
            var spec = SAMPLE.Spec.getSpec(dbContext, Id);

            if (!string.IsNullOrEmpty(spec.AcceptanceRules))
            {
                var path = Common.getGlobalKeyValue(dbContext, "AcceptanceRules_Path");
                var fileName = path + "\\" + spec.AcceptanceRules + ".py";
                if (System.IO.File.Exists(fileName))
                {
                    StreamReader sw = new StreamReader(fileName);
                    string st = sw.ReadToEnd();
                    sw.Close();
                    return st;
                }
                else
                    return "找不到指定规则文件，请联系管理员！";
            }
            else
                return "";
        }

        [HttpPost]
        public string postUpdateSpecAcceptanceRules(string Id, string AcceptanceRules)
        {
            var spec = SAMPLE.Spec.getSpec(dbContext, Id);
            var path = Common.getGlobalKeyValue(dbContext, "AcceptanceRules_Path");

            if (string.IsNullOrEmpty(spec.AcceptanceRules))
            {
                var pyid = SAMPLE._newId();
                var fileName = path + "\\" + pyid + ".py";

                using (var fs = new StreamWriter(fileName))
                {
                    fs.Write(AcceptanceRules);
                    fs.Close();
                }
                return SAMPLE.Spec.UpdateSpecAcceptanceRules(dbContext, Id, pyid);
            }
            else
            {
                var fileName = path + "\\" + spec.AcceptanceRules + ".py";

                using (var fs = new StreamWriter(fileName))
                {
                    fs.Write(AcceptanceRules);
                    fs.Close();
                }
                return "规则更新成功！";
            }
        }

        [HttpPost]
        public string postClearSpecAcceptanceRules(string Id)
        {
            // 清除关联的规则。考虑到会有运行时的样品对规则的引用，清除时并不处理规则文件，这样不会引起运行时样品报错。
            return SAMPLE.Spec.UpdateSpecAcceptanceRules(dbContext, Id, null);
        }

        [HttpPost]
        public string postUpdateSpecAcceptanceCriteria(string Id, string AcceptanceCriteria)
        {
            return SAMPLE.Spec.UpdateSpecAcceptanceCriteria(dbContext, Id, AcceptanceCriteria);
        }

        [HttpPost]
        public string postUpdateSpecLowA(string Id, string lowA)
        {
            return SAMPLE.Spec.UpdateLowA(dbContext, Id, lowA);
        }

        [HttpPost]
        public string postUpdateSpecLowB(string Id, string lowB)
        {
            return SAMPLE.Spec.UpdateLowB(dbContext, Id, lowB);
        }

        [HttpPost]
        public string postUpdateSpecHighB(string Id, string highB)
        {
            return SAMPLE.Spec.UpdateHighB(dbContext, Id, highB);
        }

        [HttpPost]
        public string postUpdateSpecHighA(string Id, string highA)
        {
            return SAMPLE.Spec.UpdateHighA(dbContext, Id, highA);
        }

        [HttpPost]
        public string postUpdateSpecStandrdValue(string Id, string standrdValue)
        {
            return SAMPLE.Spec.UpdateStandrdValue(dbContext, Id, standrdValue);
        }

        [HttpPost]
        public string postDeleteSpec(string Id)
        {
            return SAMPLE.Spec.DeleteSpec(dbContext, Id);
        }

        [HttpPost]
        public string postAddSampleSpec(string jsonStr)
        {
            SampleSpec spec = JsonConvert.DeserializeObject<SampleSpec>(jsonStr);  //反序列化，字符串转换为类
            var st = spec.AddSpec(dbContext);
            return st;
        }

        [HttpPost]
        public string postUpdateSampleSpec(string jsonStr)
        {
            SampleSpec spec = JsonConvert.DeserializeObject<SampleSpec>(jsonStr);  //反序列化，字符串转换为类
            var st = spec.UpdateSpec(dbContext, false);
            return st;
        }

        [HttpPost]
        public JsonResult GetSpecRelationAnalytes(string SpecId)
        {
            var spec = SAMPLE.Spec.getSpec(dbContext, SpecId);

            if (spec is null)
            { return null; }
            else
            { return Json(spec.getSpecRelationAnalytes(dbContext)); }
        }

        #endregion

        #region 指标集相关

        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult SpecCollection() => View();

        public ViewResult AddSpecCollection(string Id, string ModalID)
        {
            ViewData["SpecId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        public ViewResult AddSpecCollectionAnalyte(string Id, string ModalID)
        {
            ViewData["CollectionId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public string postAddSampleSpecCollection(string jsonStr)
        {
            SampleSpec spec = JsonConvert.DeserializeObject<SampleSpec>(jsonStr);  //反序列化，字符串转换为类
            var st = spec.AddSpecCollection(dbContext);
            return st;
        }

        [HttpPost]
        public string postDeleteSpecCollection(string Id)
        {
            return SAMPLE.Spec.DeleteSpecCollection(dbContext, Id);
        }

        [HttpPost]
        public string postUpdateSampleSpecCollection(string jsonStr)
        {
            SampleSpec spec = JsonConvert.DeserializeObject<SampleSpec>(jsonStr);  //反序列化，字符串转换为类
            var st = spec.UpdateSpecCollection(dbContext);
            return st;
        }

        [HttpPost]
        public JsonResult GetSpecCollectionFirstGroup()
        {
            var first = SAMPLE.Spec.getSpecCollectionList(dbContext)
                .Where(s => s.IsCollection == true)
                .Distinct(new SAMPLE.SpecFirstGroupCompare())
                .Select(s => new { s.FirstGroup });

            return Json(first);
        }

        [HttpPost]
        public JsonResult GetSpecCollectionByFirstGroup(string FirstGroup)
        {
            var first = SAMPLE.Spec.getSpecCollectionListByFirstGroup(dbContext, FirstGroup)
                .Select(s => new { s.Id, s.Code, s.Name, s.Description });

            return Json(first);
        }

        [HttpPost]
        public JsonResult GetSpecCollectionSecondGroup(string FirstGroup)
        {
            var first = SAMPLE.Spec.getSpecCollectionListByFirstGroup(dbContext, FirstGroup)
                .Where(s => s.IsCollection == true)
                .Distinct(new SAMPLE.SpecSecondGroupCompare())
                .Select(s => new { s.SecondGroup });

            return Json(first);
        }

        [HttpPost]
        public JsonResult GetSpecCollectionFirstAndBySecond(string FirstGroup, string SecondGroup, string limit, string offset, bool Enable=false)
        {
            if (limit == null) // 如果没传递分页信息则不分页
            {
                if (Enable == false)
                    return Json(SAMPLE.Spec.getSpecCollectionFirstAndBySecond(dbContext, FirstGroup, SecondGroup));
                else
                    return Json(SAMPLE.Spec.getSpecCollectionFirstAndBySecond(dbContext, FirstGroup, SecondGroup)
                        .Where(s => s.Enable == true).ToList());
            }

            var res = new Common.PageHelper();
            if (Enable == false)
            {
                var first = SAMPLE.Spec.getSpecCollectionFirstAndBySecond(dbContext, FirstGroup, SecondGroup)
                        .Skip(int.Parse(offset)).Take(int.Parse(limit))
                        .ToArray();

                res.total = SAMPLE.Spec.getSpecCollectionFirstAndBySecond(dbContext, FirstGroup, SecondGroup).Count;
                res.rows = first;
            }
            else
            {
                var first = SAMPLE.Spec.getSpecCollectionFirstAndBySecond(dbContext, FirstGroup, SecondGroup)
                        .Where(s => s.Enable == true)
                        .Skip(int.Parse(offset)).Take(int.Parse(limit))
                        .ToArray();

                res.total = SAMPLE.Spec.getSpecCollectionFirstAndBySecond(dbContext, FirstGroup, SecondGroup)
                        .Where(s => s.Enable == true).ToList().Count;
                res.rows = first;
            }

            return Json(res);
        }

        [HttpPost]
        public string AddSpecCollectionAanylte(string jsonStr)
        {
            SampleSpec spec = JsonConvert.DeserializeObject<SampleSpec>(jsonStr);  //反序列化，字符串转换为类
            var st = spec.addSpecCollectionAanylte(dbContext);
            return st;
        }

        [HttpPost]
        public JsonResult GetSpecCollectionAnalytes(string CollectionId)
        {
            var anaList = SAMPLE.Spec.getSpecCollectionAnayltes(dbContext, CollectionId);
            return Json(anaList);
        }

        [HttpPost]
        public JsonResult GetSpecCollectionAnalytesByTestRelationId(string TestRelationId)
        {
            var specCollection = SAMPLE.TestRelation.getTestRelation(dbContext, TestRelationId);
            var anaList = SAMPLE.Spec.getSpecCollectionAnayltes(dbContext, specCollection.SpecCollectionId);
            return Json(anaList);
        }

        [HttpPost]
        public string DelteSpecCollectionAanylte(string SpecId)
        {
            SAMPLE.Spec.DeleteSpecCollectionAnalyte(dbContext, SpecId);
            return "删除成功";
        }

        [HttpPost]
        public string UpdateRelationSpecAndAanylte(string SpecID, string AnalyteID)
        {
            SAMPLE.UpdateRelationSpecAndAanylte(dbContext, SpecID, AnalyteID);
            return "更新成功";
        }

        [HttpPost]
        public string DelteRelationSpecAndAanylte(string AnalyteID)
        {
            SAMPLE.DelteRelationSpecAndAanylte(dbContext, AnalyteID);
            return "删除成功";
        }

        #endregion

        #region 样品定义

        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult SampleDefinition() => View();

        [HttpPost]
        public JsonResult GetSampleDefinitionClassification()
        {
            var cf = SAMPLE.SampleDefinition.getSampleDefinitionList(dbContext)
                .Distinct(new SAMPLE.SampleDefinitionClassificationCompare()).Select(s => new { s.Classification });
            return Json(cf);
        }

        [HttpPost]
        public JsonResult GetSampleDefinitionGenricClass(string Site, string Classification)
        {
            if (string.IsNullOrEmpty(Site))
            {
                var gc = SAMPLE.SampleDefinition.getSampleDefinitionList(dbContext)
                    .Where(s => s.Classification == Classification)
                    .Distinct(new SAMPLE.SampleDefinitionGenricClassCompare()).Select(s => new { s.GenricClass });
                return Json(gc);
            }
            else
            {
                var gc = SAMPLE.SampleDefinition.getSampleDefinitionList(dbContext)
                    .Where(s => s.Classification == Classification && s.Site == Site)
                    .Distinct(new SAMPLE.SampleDefinitionGenricClassCompare()).Select(s => new { s.GenricClass });
                return Json(gc);
            }
        }

        [HttpPost]
        public JsonResult GetSampleDefinitionListClassAndGenric(string Classification, string GenricClass,string Site, string Group, string limit, string offset)
        {
            var res = new Common.PageHelper();

            if (string.IsNullOrEmpty(Site))
            {
                var sdList = SAMPLE.SampleDefinition.getSampleDefinitionListClassAndGenric(dbContext, Classification, GenricClass)
                    .Select(x => new { x.Id, x.Name, x.DefaultNumber, x.Description, x.Site, x.Group, x.WorkFlowName, x.ReportName ,
                        x.IsRelease, x.SamplingPoint, x.IsRetention, x.RetentionConfigId })
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();

                res.total = SAMPLE.SampleDefinition.getSampleDefinitionListClassAndGenric(dbContext, Classification, GenricClass).Count;
                res.rows = sdList;
            }
            if (!string.IsNullOrEmpty(Site) && string.IsNullOrEmpty(Group))
            {
                var sdList = SAMPLE.SampleDefinition.getSampleDefinitionListClassAndGenric(dbContext, Classification, GenricClass)
                    .Where(s => s.Site == Site)
                    .Select(x => new { x.Id, x.Name, x.DefaultNumber, x.Description, x.Site, x.Group, x.WorkFlowName, x.ReportName, 
                        x.IsRelease, x.SamplingPoint, x.IsRetention, x.RetentionConfigId })
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();

                res.total = SAMPLE.SampleDefinition.getSampleDefinitionListClassAndGenric(dbContext, Classification, GenricClass).Count;
                res.rows = sdList;
            }
            if (!string.IsNullOrEmpty(Site) && !string.IsNullOrEmpty(Group))
            {
                var sdList = SAMPLE.SampleDefinition.getSampleDefinitionListClassAndGenric(dbContext, Classification, GenricClass)
                    .Where(s => s.Site == Site && s.Group == Group)
                    .Select(x => new { x.Id, x.Name, x.DefaultNumber, x.Description, x.Site, x.Group, x.WorkFlowName, x.ReportName, 
                        x.IsRelease, x.SamplingPoint, x.IsRetention, x.RetentionConfigId })
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();

                res.total = SAMPLE.SampleDefinition.getSampleDefinitionListClassAndGenric(dbContext, Classification, GenricClass).Count;
                res.rows = sdList;
            }
            return Json(res);
        }

        [HttpPost]
        public JsonResult GetSampleDefinitionListByName(string Name, string limit, string offset)
        {
            var sdList = SAMPLE.SampleDefinition.getSampleDefinitionByName(dbContext, Name)
                .Select(x => new { x.Id, x.Name, x.Description, x.Site, x.Group, x.WorkFlowName, x.ReportName })
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.SampleDefinition.getSampleDefinitionByName(dbContext, Name).Count;
            res.rows = sdList;

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetSampleDefinition(string Id)
        {
            var sd = SAMPLE.SampleDefinition.getSampleDefinition(dbContext, Id);
            return Json(sd);
        }

        [HttpPost]
        public string postAddSampleDefinition(string jsonStr)
        {
            SampleSampleDefinition sd = JsonConvert.DeserializeObject<SampleSampleDefinition>(jsonStr);  //反序列化，字符串转换为类
            var st = sd.AddSampleDefinition(dbContext);
            return st;
        }

        [HttpPost]
        public string postUpdateSampleDefinition(string jsonStr)
        {
            SampleSampleDefinition sd = JsonConvert.DeserializeObject<SampleSampleDefinition>(jsonStr);  //反序列化，字符串转换为类
            var st = sd.UpdateSampleDefinition(dbContext);
            return st;
        }

        [HttpPost]
        public string postDeleteSampleDefinition(string Id)
        {
            return SAMPLE.SampleDefinition.DeleteSampleDefinition(dbContext, Id);
        }

        [HttpPost]
        public string CopySampleDefinition(string Id)
        {
            return SAMPLE.SampleDefinition.CopySampleDefinition(dbContext, Id);
        }

        [HttpPost]
        public ViewResult AddSampleDefinition(string Id, string ModalID)
        {
            ViewData["SampleDefinitionId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetSiteList()
        {
            var list = Common.SiteGroup.getSiteGroupList(dbContext)
                .Distinct(new Common.SiteGroupSiteCompare())
                .Select(x => x.Site);

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetWorkFlowDefinitionList(string Type)
        {
            var list = dbContext.Definition.Where(s => s.Type == Type).ToList()
                .Select(x => new { x.Id, x.Name });
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetReportList()
        {
            var path = dbContext.Global.Where(s => s.KeyName == "ReportTemplate_Path").FirstOrDefault().KeyValue;
            var files = Directory.GetFiles(path, "*.docx");

            var temp = new string[files.Length];
            for (int i = 0; i < files.Length; i++)
            {
                var st = files[i].Split('\\');
                temp[i] = st[st.Length - 1];
            }

            return Json(temp);
        }

        [HttpPost]
        public JsonResult GetWorkGroupList(string Site) // 如果不传Site,则获得所有组
        {
            if (Site.IsNullOrEmpty())
            {
                var list = Common.SiteGroup.getSiteGroupList(dbContext)
                    .Select(s => new { s.Id, s.WorkGroup });
                return Json(list);
            }
            else
            {
                var list = Common.SiteGroup.getSiteGroupList(dbContext)
                    .Where(s => s.Site == Site)
                    .Select(s => new { s.Id, s.WorkGroup });
                return Json(list);
            }
        }

        [HttpPost]
        public JsonResult GetSampleDefinitionRelationAnalytes(string SampleDefinitonId)
        {
            return Json(SAMPLE.SampleDefinition.getRelationAnalytes(dbContext, SampleDefinitonId));
        }

        [HttpPost]
        public ViewResult AddRelationSDAndAnalyte(string SampleDefinitonId, string ModalID)
        {
            ViewData["SampleDefinitonId"] = SampleDefinitonId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetRelationTestDefinition(string SampleDefinitonId)
        {
            var list = SAMPLE.SampleDefinition.getRelationTestDefinition(dbContext, SampleDefinitonId)
                .ToList();

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetRelationSpecCollection(string SampleDefinitonId)
        {
            var tdf = SAMPLE.SampleDefinition.getRelationSpecCollection(dbContext, SampleDefinitonId);

            if (tdf is null)
            { return null; }
            else
            {
                return Json(tdf);
            }
        }

        [HttpPost]
        public JsonResult GetTestDifinitonAnalytesByRelationId(string RelationId)
        {
            var rel = SAMPLE.Relation.getRelation(dbContext, RelationId);
            var test = SAMPLE.TestDefinition.getTestDefinition(dbContext, rel.IncludedId);
            var list = test.getTestDefinitionRelationAnalytes(dbContext);

            return Json(list);
        }

        [HttpPost]
        public ViewResult AddRelationSDAndTestDefinition(string SampleDefinitonId, string SampleLoginId, string ModalID)
        {
            ViewData["SampleDefinitonId"] = SampleDefinitonId;
            ViewData["SampleLoginId"] = SampleLoginId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult AddSampleSpecCollection(string SampleDefinitionId, string SampleLoginId, string ModalID)
        {
            ViewData["SampleDefinitionId"] = SampleDefinitionId;
            ViewData["SampleLoginId"] = SampleLoginId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public string AddRelationSDAndSpecCollection(string SampleDefinitionId, string SpecCollectionId)
        {
            return SAMPLE.SampleDefinition.AddRelationSpecCollection(dbContext, SampleDefinitionId, SpecCollectionId);
        }

        [HttpPost]
        public string DelteRelationSpecCollection(string RelationId)
        {
            return SAMPLE.SampleDefinition.DelteRelationSpecCollection(dbContext, RelationId);
        }

        [HttpPost]
        public string UpdateSampleSpecCollectionIsDefault(string Id)
        {
            return SAMPLE.Relation.UpdateSampleSpecCollectionIsDefault(dbContext, Id);
        }

        [HttpPost]
        public JsonResult GetSpecCollectionAnalytesByRelationId(string RelationId)
        {
            var specCollection = SAMPLE.Relation.getRelation(dbContext, RelationId);
            var anaList = SAMPLE.Spec.getSpecCollectionAnayltes(dbContext, specCollection.IncludedId);
            return Json(anaList);
        }

        [HttpPost]
        public string AddRelationSDAndAanylte(string SampleDefinitionId, string AnalyteID)
        {
            return SAMPLE.SampleDefinition.AddRelationAanylte(dbContext, SampleDefinitionId, AnalyteID);
        }

        [HttpPost]
        public string DelteRelationSDAndAanylte(string RelationId)
        {
            return SAMPLE.SampleDefinition.DelteRelationAanylte(dbContext, RelationId);
        }

        [HttpPost]
        public string AddRelationSDAndTestDefinitions(string SampleDefinitionId, string TestDefinitionId)
        {
            return SAMPLE.SampleDefinition.AddRelationTestDefinition(dbContext, SampleDefinitionId, TestDefinitionId);
        }

        [HttpPost]
        public string DelteRelationSDAndTestDefinition(string RelationId)
        {
            return SAMPLE.SampleDefinition.DelteRelationTestDefinition(dbContext, RelationId);
        }

        [HttpPost]
        public ViewResult SetSkipWorkflow(string SampleDefefinitionId, string ModalID, string SetSampleLogin="False")
        {
            ViewData["SetSampleLogin"] = SetSampleLogin;
            ViewData["SampleDefefinitionId"] = SampleDefefinitionId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetSampleDefinitionWorkflowStepSequence(string SampleDefefinitionId)
        {
            var sd = SAMPLE.SampleDefinition.getSampleDefinition(dbContext, SampleDefefinitionId);
            if (sd == null || sd.WorkFlowId == null)
                return null;

            var list = SAMPLE.GetWorkflowStepSequence(sd.WorkFlowId, sd.SkipSequence);
            if (list == null)
                return null;
            else
                return Json(list);
        }

        [HttpPost]
        public string UpdateSampleDefenitionSkipSequence(string SampleDefefinitionId, string SkipSequence)
        {
            var st = SAMPLE.SampleDefinition.UpdateSkipSequence(dbContext, SampleDefefinitionId, SkipSequence);
            return st;
        }

        [HttpPost]
        public string UpdateSampleDefenitionIsRelease(string SampleDefefinitionId, string IsRelease)
        {
            var definition = SAMPLE.SampleDefinition.getSampleDefinition(dbContext, SampleDefefinitionId);
            definition.IsRelease = IsRelease == "true"?true:false;
            dbContext.Update(definition);
            dbContext.SaveChanges();

            return "发布项更新成功！";
        }

        [HttpPost]
        public string UpdateSampleDefenitionIsRetention(string SampleDefefinitionId, string IsRetention)
        {
            var definition = SAMPLE.SampleDefinition.getSampleDefinition(dbContext, SampleDefefinitionId);
            definition.IsRetention = IsRetention == "true" ? true : false;
            dbContext.Update(definition);
            dbContext.SaveChanges();

            return "留样项更新成功！";
        }

        [HttpPost]
        public string UpdateSampleDefenitionRetentionConfigId(string SampleDefefinitionId, string RetentionConfigId)
        {
            var definition = SAMPLE.SampleDefinition.getSampleDefinition(dbContext, SampleDefefinitionId);
            definition.RetentionConfigId = RetentionConfigId;
            dbContext.Update(definition);
            dbContext.SaveChanges();

            return "留样配置更新成功！";
        }

        #endregion

        #region 样品组管理

        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult SampleGroup() => View();

        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult AddSampleGroup(string SampleGroupId, string ModalID)
        {
            ViewData["SampleGroupId"] = SampleGroupId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetSampleGroup(string SampleGroupId)
        {
            var sg = SAMPLE.SampleGroup.getSampleGroupList(dbContext)
                .Where(s => s.Id == SampleGroupId).FirstOrDefault();
            return Json(sg);
        }

        [HttpPost]
        public JsonResult GetSampleGroupType()
        {
            var type = SAMPLE.SampleGroup.getSampleGroupList(dbContext)
                .Where(s => s.Type != null)
                .Distinct(new SAMPLE.SampleGroupTypeCompare()).Select(s => new { s.Type });
            return Json(type);
        }

        [HttpPost]
        public JsonResult GetSampleGroupByType(string Type, string limit, string offset)
        {
            List<SampleSampleGroup> list = new List<SampleSampleGroup>();
            int total = 0;

            if (Type != "全部")
            {
                list = SAMPLE.SampleGroup.getSampleGroupList(dbContext)
                    .Where(s => s.Type == Type && s.SampleGroupId == null)
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToList();
                total = SAMPLE.SampleGroup.getSampleGroupList(dbContext)
                    .Where(s => s.Type == Type && s.SampleGroupId == null)
                    .ToList().Count;
            }
            else
            {
                list = SAMPLE.SampleGroup.getSampleGroupList(dbContext)
                    .Where(s => s.SampleGroupId == null && s.Type != null)
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToList();
                total = SAMPLE.SampleGroup.getSampleGroupList(dbContext)
                    .Where(s => s.SampleGroupId == null && s.Type != null)
                    .ToList().Count;
            }

            var res = new Common.PageHelper();
            res.total = total;
            res.rows = list.ToArray();

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetSampleGroupList(string Type)
        {
            if (Type == "全部")
            {
                var list = SAMPLE.SampleGroup.getSampleGroupList(dbContext).Where(s => s.Type != null)
                    .Select(s => new { s.Id, s.Name }).ToList();
                return Json(list);
            }
            else
            {
                var list = SAMPLE.SampleGroup.getSampleGroupList(dbContext).Where(s => s.Type == Type)
                    .Select(s => new { s.Id, s.Name }).ToList();
                return Json(list);
            }
        }

        public JsonResult GetSamplesBySGID(string SampleGroupId)
        {
            var list = SAMPLE.SampleGroup.getSampleGroupBySGID(dbContext, SampleGroupId);
            return Json(list);
        }

        [HttpPost]
        public string AddSampleToSampleGroup(string SampleDefinitionList, string SampleGroupId)
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return SAMPLE.Sample.AddSampleToSampleGroup(dbContext, SampleDefinitionList, user, SampleGroupId);
        }

        [HttpPost]
        public string postAddSampleGroup(string jsonStr)
        {
            SampleSampleGroup sd = JsonConvert.DeserializeObject<SampleSampleGroup>(jsonStr);  //反序列化，字符串转换为类
            var st = sd.AddSampleGroup(dbContext);
            return st;
        }

        [HttpPost]
        public string postUpdateSampleGroup(string jsonStr)
        {
            SampleSampleGroup sd = JsonConvert.DeserializeObject<SampleSampleGroup>(jsonStr);  //反序列化，字符串转换为类
            var st = sd.UpdateSampleGroup(dbContext);
            return st;
        }

        [HttpPost]
        public string postDeleteSampleGroup(string Id)
        {
            return SAMPLE.SampleGroup.DeleteSampleGroup(dbContext, Id);
        }

        [HttpPost]
        public string postDeleteSGSample(string Id)
        {
            return SAMPLE.SampleGroup.DeleteSGSample(dbContext, Id);
        }

        [HttpPost]
        public string UpdateSampleGroupNumber(string Id, string number)
        {
            return SAMPLE.SampleGroup.UpdateSampleGroupNumber(dbContext, Id, number);
        }

        [HttpPost]
        public JsonResult GetSampleGroupByName(string Name, string limit, string offset)
        {
            var sdList = SAMPLE.SampleGroup.getSampleGroupByName(dbContext, Name)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.SampleGroup.getSampleGroupByName(dbContext, Name).Count;
            res.rows = sdList;

            return Json(res);
        }

        #endregion

        #region 测试定义

        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult TestDefinition()
        {
            return View(SAMPLE.TestDefinition.getTestDefinitionList(dbContext).Distinct(new SAMPLE.TestDefinitionTestNameCompare()));
        }

        [HttpPost]
        public ViewResult TestAnalyteCalculationRules(string TestRelationId, string ModalID)
        {
            ViewData["TestRelationId"] = TestRelationId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult AddTestDefinition(string Id, string ModalID)
        {
            ViewData["TestDefinitionId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult AddTestSpecCollection(string TestDefinitionId, string ModalID)
        {
            ViewData["TestDefinitionId"] = TestDefinitionId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult AddTestMethod(string TestDefinitionId, string ModalID)
        {
            ViewData["TestDefinitionId"] = TestDefinitionId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetTestDefinitionFirstGroup()
        {
            var first = SAMPLE.TestDefinition.getTestDefinitionList(dbContext)
                .Distinct(new SAMPLE.TestDefinitionFirstGroupCompare())
                .Select(s => new { s.FirstGroup });
            return Json(first);
        }

        [HttpPost]
        public JsonResult GetTestDefinitionSecondGroup(string FirstGroup)
        {
            var second = SAMPLE.TestDefinition.getTestDefinitionListByFirstGroup(dbContext, FirstGroup)
                .Distinct(new SAMPLE.TestDefinitionSecondGroupCompare())
                .Select(s => new { s.SecondGroup });
            return Json(second);
        }

        [HttpPost]
        public JsonResult GetTestDefinitionListFirstAndBySecondAllField(string FirstGroup, string SecondGroup)
        {
            var list = SAMPLE.TestDefinition.getTestDefinitionListFirstAndBySecond(dbContext, FirstGroup, SecondGroup);
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetTestDefinitionListFirstAndBySecond(string FirstGroup, string SecondGroup)
        {
            var list = SAMPLE.TestDefinition.getTestDefinitionListFirstAndBySecond(dbContext, FirstGroup, SecondGroup)
                .Select(s => new { s.Id, s.TestName, s.Description, s.FirstGroup, s.SecondGroup, s.Version, s.ReleaseStatus })
                .ToList();

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetTestDefinition(string Id)
        {
            var td = SAMPLE.TestDefinition.getTestDefinition(dbContext, Id);
            return Json(td);
        }

        [HttpPost]
        public string postAddTestDefinition(string jsonStr)
        {
            SampleTestDefinition td = JsonConvert.DeserializeObject<SampleTestDefinition>(jsonStr);  //反序列化，字符串转换为类
            var st = td.AddTestDefinition(dbContext);
            return st;
        }

        [HttpPost]
        public string postUpdateTestDefinition(string jsonStr)
        {
            SampleTestDefinition td = JsonConvert.DeserializeObject<SampleTestDefinition>(jsonStr);  //反序列化，字符串转换为类
            var st = td.UpdateTestDefinition(dbContext, false);
            return st;
        }

        [HttpPost]
        public string postDeleteTestDefinition(string Id)
        {
            return SAMPLE.TestDefinition.DeleteTestDefinition(dbContext, Id);
        }

        [HttpPost]
        public JsonResult GetTestDefinitionRelationAnalytes(string TestDefinitionId)
        {
            var tdf = SAMPLE.TestDefinition.getTestDefinition(dbContext, TestDefinitionId);

            if (tdf is null)
            { return null; }
            else
            {
                return Json(tdf.getTestDefinitionRelationAnalytes(dbContext));
            }
        }

        [HttpPost]
        public JsonResult GetTestDefinitionRelationSpecCollection(string TestDefinitionId)
        {
            var tdf = SAMPLE.TestDefinition.getTestDefinition(dbContext, TestDefinitionId);

            if (tdf is null)
            { return null; }
            else
            {
                return Json(tdf.getTestDefinitionRelationSpecCollection(dbContext));
            }
        }

        [HttpPost]
        public JsonResult GetTestDefinitionRelationMethod(string TestDefinitionId)
        {
            var tdf = SAMPLE.TestDefinition.getTestDefinition(dbContext, TestDefinitionId);

            if (tdf is null)
            { return null; }
            else
            {
                return Json(tdf.getTestDefinitionRelationMethod(dbContext));
            }
        }

        [HttpPost]
        public string GetTestRelationCalculationRules(string Id)
        {
            var ta = SAMPLE.TestRelation.getTestRelation(dbContext, Id);

            if (!string.IsNullOrEmpty(ta.CalculationRules))
            {
                var path = Common.getGlobalKeyValue(dbContext, "CalculationRules_Path");
                var fileName = path + "\\" + ta.CalculationRules + ".py";
                if (System.IO.File.Exists(fileName))
                {
                    StreamReader sw = new StreamReader(fileName);
                    string st = sw.ReadToEnd();
                    sw.Close();
                    return st;
                }
                else
                    return "找不到指定规则文件，请联系管理员！";
            }
            else
                return "";

        }

        [HttpPost]
        public string CheckHasCalculationRules(string TestRelationId)
        {
            var ta = SAMPLE.TestRelation.getTestRelation(dbContext, TestRelationId);

            if (string.IsNullOrEmpty(ta.CalculationRules))
                return "false";
            else
                return "true";
        }

        [HttpPost]
        public string postUpdateTestRelationCalculationRules(string Id, string CalculationRules)
        {
            var ta = SAMPLE.TestRelation.getTestRelation(dbContext, Id);
            var path = Common.getGlobalKeyValue(dbContext, "CalculationRules_Path");

            if (string.IsNullOrEmpty(ta.CalculationRules))
            {
                var pyid = SAMPLE._newId();
                var fileName = path + "\\" + pyid + ".py";

                using (var fs = new StreamWriter(fileName))
                {
                    fs.Write(CalculationRules);
                    fs.Close();
                }
                return SAMPLE.TestRelation.UpdateTestRelationCalculationRules(dbContext, Id, pyid);
            }
            else
            {
                var fileName = path + "\\" + ta.CalculationRules + ".py";

                using (var fs = new StreamWriter(fileName))
                {
                    fs.Write(CalculationRules);
                    fs.Close();
                }
                return "规则更新成功！";
            }
        }


        public string postClearTestRelationCalculationRules(string Id)
        {
            // 清除关联的规则。考虑到会有运行时的样品对规则的引用，清除时并不处理规则文件，这样不会引起运行时样品报错。
            return SAMPLE.TestRelation.ClearTestRelationCalculationRules(dbContext, Id);
        }

        [HttpPost]
        public string AddRelationTestDefinitionAndAanylte(string jsonStr)
        {
            SampleTestRelation tal = JsonConvert.DeserializeObject<SampleTestRelation>(jsonStr);  //反序列化，字符串转换为类
            var st = tal.AddTestRelation(dbContext);
            return st;
        }

        [HttpPost]
        public string AddRelationTestDefinitionAndSpecCollection(string jsonStr)
        {
            SampleTestRelation tal = JsonConvert.DeserializeObject<SampleTestRelation>(jsonStr);  //反序列化，字符串转换为类
            var st = tal.AddSpecCollection(dbContext);
            return st;
        }

        [HttpPost]
        public string AddRelationTestDefinitionAndMethod(string jsonStr)
        {
            SampleTestRelation tal = JsonConvert.DeserializeObject<SampleTestRelation>(jsonStr);  //反序列化，字符串转换为类
            var st = tal.AddMethod(dbContext);
            return st;
        }

        [HttpPost]
        public string DelteRelationTestDefinitionAndAanylte(string TestRelationID)
        {
            return SAMPLE.TestRelation.DeleteTestRelation(dbContext, TestRelationID);
        }

        [HttpPost]
        public string UpdateTestRelationCalculationRules(string Id, string CalculationRules)
        {
            return SAMPLE.TestRelation.UpdateTestRelationCalculationRules(dbContext, Id, CalculationRules);
        }

        [HttpPost]
        public string postUpdateTestRelationDetectionTimes(string Id, string times)
        {
            return SAMPLE.TestRelation.UpdateTestRelationDetectionTimes(dbContext, Id, times);
        }

        [HttpPost]
        public string postUpdateRelationRepeat(string Id, string Repeat)
        {
            return SAMPLE.Relation.UpdateRepeat(dbContext, Id, Repeat);
        }

        [HttpPost]
        public string SetSpecCollectionIsDefault(string Id)
        {
            return SAMPLE.TestRelation.UpdateIsDefault(dbContext, "SpecCollection", Id);
        }

        [HttpPost]
        public string SetMethodIsDefault(string Id)
        {
            return SAMPLE.TestRelation.UpdateIsDefault(dbContext, "Method", Id);
        }
        #endregion

        #region 方法管理

        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult Method()
        {
            return View(SAMPLE.Method.getMethodList(dbContext).Distinct(new SAMPLE.MethodTypeCompare()));
        }

        public ViewResult AddMethod(string Id, string ModalID)
        {
            ViewData["MethodId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetMethod(string Id)
        {
            var sd = SAMPLE.Method.getMethod(dbContext, Id);
            return Json(sd);
        }

        [HttpPost]
        public JsonResult GetMethodListByType(string Type, string limit, string offset)
        {
            var list = SAMPLE.Method.getMethodListByType(dbContext, Type)
                .Select(x => new
                {
                    x.Id,
                    x.Name,
                    x.Code,
                    x.Description,
                    x.Type,
                    x.EffectiveDate,
                    x.ExpireDate,
                    x.RecordSheet,
                    x.Version,
                    x.Status,
                    x.Enable
                })
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.Method.getMethodListByType(dbContext, Type).Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public JsonResult UpdateMethodEnable(string Id, string Enable)
        {
            var st = SAMPLE.Method.UpdateMethodEnable(dbContext, Id, Enable);
            return Json(st);
        }

        [HttpPost]
        public JsonResult GetMethodType()
        {
            var cf = SAMPLE.Method.getMethodList(dbContext)
                .Distinct(new SAMPLE.MethodTypeCompare()).Select(s => new { s.Type });
            return Json(cf);
        }

        [HttpPost]
        public JsonResult GetMethodCodeByType(string Type)
        {
            var list = SAMPLE.Method.getMethodListByType(dbContext, Type)
                .Where(m => m.Type == Type)
                .Select(s => new { s.Id, s.Code })
                .OrderBy(x => x.Code);

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetRecordSheet()
        {
            var arrary = SAMPLE.Method.GetRecordSheet(dbContext);
            return Json(arrary);
        }

        [HttpPost]
        public string postAddMethod(string jsonStr)
        {
            SampleMethod sd = JsonConvert.DeserializeObject<SampleMethod>(jsonStr);  //反序列化，字符串转换为类
            var st = sd.AddMethod(dbContext);
            return st;
        }

        [HttpPost]
        public string postUpdateMethod(string jsonStr)
        {
            SampleMethod sd = JsonConvert.DeserializeObject<SampleMethod>(jsonStr);  //反序列化，字符串转换为类
            var st = sd.UpdateMethod(dbContext);
            return st;
        }

        [HttpPost]
        public string postDeleteMethod(string Id)
        {
            return SAMPLE.Method.DeleteMethod(dbContext, Id);
        }

        #endregion

        #region 样品登录

        [Authorize(Roles = "Admin,样品登录")]
        public ViewResult SampleLogin() => View();

        [HttpPost]
        public ViewResult SelectSampleDefinition(string ModalID, string SampleGroupId)
        {
            ViewData["ModalID"] = ModalID;
            ViewData["SampleGroupId"] = SampleGroupId;
            return View();
        }

        [HttpPost]
        public ViewResult SelectSampleGroup(string ModalID)
        {
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult SampleBatch(string ModalID, string SampleBatchId)
        {
            ViewData["ModalID"] = ModalID;
            ViewData["SampleBatchId"] = SampleBatchId;
            return View();
        }

        [HttpPost]
        public ViewResult AddSampleLoginAnalyte(string SampleLoginId, string ModalID)
        {
            ViewData["SampleLoginId"] = SampleLoginId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public string postAddSampleLoginAnalyte(string SampleLoginId, string AnalyteID)
        {
            return SAMPLE.LoginRelation.AddSampleLoginAanylte(dbContext, SampleLoginId, AnalyteID);
        }

        [HttpPost]
        public JsonResult GetSampleLoginList(string limit, string offset)
        {
            var list = SAMPLE.Sample.getSampleLoginList(dbContext)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.Sample.getSampleLoginList(dbContext).Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetSampleLogin(string Id)
        {
            return Json(SAMPLE.Sample.getSampleLogin(dbContext, Id));
        }

        [HttpPost]
        public string AddSampleLogin(string BatchId, string SampleDefinitionList)
        {
            if (Common.getGlobalKeyValue(dbContext, "SampleLogin_LockBatchId") == "True") 
            {
                if (BatchId.IsNullOrEmpty())
                    return "必需输入批次号！";
            }

            if (BatchId.IsNullOrEmpty()) // 在系统不限制批次号的情况下，没输入的批次号统一置为 null
                BatchId = null;

            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return SAMPLE.Sample.AddSampleDefinition(dbContext, SampleDefinitionList, BatchId, user).GetAwaiter().GetResult();
        }

        [HttpPost]
        public string AddSampleBatch(string jsonStr)
        {
            SampleSampleBatch batch = JsonConvert.DeserializeObject<SampleSampleBatch>(jsonStr);  //反序列化，字符串转换为类
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            batch.PersonId = user.Id;
            batch.PersonName = user.FullName;
            dbContext.Add(batch);
            dbContext.SaveChanges();

            return "样品单添加成功！";
        }

        [HttpPost]
        public bool CheckSampleBatch(string BatchId) // 检查 BatchId 是否已在样品单中
        {
            var batch = dbContext.SampleSampleBatch.FirstOrDefault(s => s.BatchId == BatchId);
            if (batch == null)
                return false;
            else
                return true;
        }

        [HttpPost]
        public JsonResult GetSampleBatch(string BatchId) // 获得样品单信息
        {
            var batch = dbContext.SampleSampleBatch.Where(s => s.BatchId == BatchId).ToList();
            return Json(batch);
        }

        [HttpPost]
        public string LoginSampleGroup(string BatchId, string SampleGroupList)
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var SampleDefinitionList = SAMPLE.SampleGroup.GetSampleDefinitionList(dbContext, SampleGroupList);
            return SAMPLE.Sample.AddSampleDefinition(dbContext, SampleDefinitionList.Substring(0, SampleDefinitionList.Length - 1), BatchId, user).GetAwaiter().GetResult();
        }

        [HttpPost]
        public string postUpdateSampleLoginBatchId(string Id, string BatchId)
        {
            return SAMPLE.Sample.UpdateSampleLoginBatchId(dbContext, Id, BatchId);
        }

        [HttpPost]
        public string postUpdateSampleLoginSampleNumber(string Id, string SampleNumber)
        {
            return SAMPLE.Sample.UpdateSampleLoginSampleNumber(dbContext, Id, SampleNumber);
        }

        [HttpPost]
        public string UpdateAssignPerson(string Id, string PersonId, string PersonName)
        {
            return SAMPLE.Sample.UpdateSampleLoginAssignPerson(dbContext, Id, PersonId, PersonName);
        }

        [HttpPost]
        public string UpdateAssignGroup(string Id, string GroupId, string GroupName)
        {
            return SAMPLE.Sample.UpdateSampleLoginAssignGroup(dbContext, Id, GroupId, GroupName);
        }

        [HttpPost]
        public string postUpdateSampleLoginDetectionTimes(string Id, string DetectionTimes)
        {
            return SAMPLE.Sample.UpdateSampleLoginDetectionTimes(dbContext, Id, DetectionTimes);
        }

        [HttpPost]
        public JsonResult GetSampleLoginRelationAnalytes(string SampleId)
        {
            return Json(SAMPLE.Sample.getRelationAnalytes(dbContext, SampleId));
        }

        [HttpPost]
        public JsonResult GetSampleLoginRelationTestDefinition(string SampleId)
        {
            var list = SAMPLE.Sample.getRelationTestDefinition(dbContext, SampleId)
                .ToList();

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetSampleLoginRelationMethod(string TestId)
        {
            var tdf = SAMPLE.Sample.getTestRelationMethod(dbContext, TestId);

            if (tdf is null)
            { return null; }
            else
            {
                return Json(tdf);
            }
        }

        [HttpPost]
        public JsonResult GetSampleLoginRelationSpecCollection(string TestId)
        {
            var tdf = SAMPLE.Sample.getTestRelationSpecCollection(dbContext, TestId);

            if (tdf is null)
            { return null; }
            else
            {
                return Json(tdf);
            }
        }

        [HttpPost]
        public JsonResult GetSpecCollectionAnalytesBySampleLoginRelation(string LoginRelationId)
        {
            var specCollection = SAMPLE.LoginRelation.getLoginRelation(dbContext, LoginRelationId);
            var anaList = SAMPLE.Spec.getSpecCollectionAnayltes(dbContext, specCollection.SpecCollectionId);
            return Json(anaList);
        }

        [HttpPost]
        public JsonResult GetSampleLoginSpecCollection(string SampleId)
        {
            var tdf = SAMPLE.Sample.getRelationSpecCollection(dbContext, SampleId);

            if (tdf is null)
            { return null; }
            else
            {
                return Json(tdf);
            }
        }

        [HttpPost]
        public JsonResult GetTestDifinitonAnalytesByLoginRelationId(string RelationId)
        {
            var list = SAMPLE.Sample.getTestRelationAnalytes(dbContext, RelationId);

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetSpecCollectionAnalytesByLoginRelationId(string LoginRelationId)
        {
            var specCollection = SAMPLE.LoginRelation.getLoginRelation(dbContext, LoginRelationId);
            var anaList = SAMPLE.Spec.getSpecCollectionAnayltes(dbContext, specCollection.SpecCollectionId);
            return Json(anaList);
        }

        [HttpPost]
        public JsonResult GetSampleLoginWorkflowStepSequence(string SampleLoginId)
        {
            var sl = SAMPLE.Sample.getSampleLogin(dbContext, SampleLoginId);
            if (sl == null || sl.WorkFlowId == null)
                return null;

            var list = SAMPLE.GetWorkflowStepSequence(sl.WorkFlowId, sl.SkipSequence);
            if (list == null)
                return null;
            else
                return Json(list);
        }

        [HttpPost]
        public string UpdateRelationMethodIsDefault(string Id)
        {
            return SAMPLE.LoginRelation.UpdateIsDefault(dbContext, "Method", Id);
        }

        [HttpPost]
        public string UpdateRelationSpecCollectionIsDefault(string Id)
        {
            return SAMPLE.LoginRelation.UpdateIsDefault(dbContext, "SpecCollection", Id);
        }

        [HttpPost]
        public string UpdateRelationSampleSpecIsDefault(string Id)
        {
            return SAMPLE.LoginRelation.UpdateIsDefault(dbContext, "SampleSpecCollection", Id);
        }

        [HttpPost]
        public string UpdateSampleLoginSkipSequence(string SampleLoginId, string SkipSequence)
        {
            var st = SAMPLE.Sample.UpdateSkipSequence(dbContext, SampleLoginId, SkipSequence);

            return st;
        }

        [HttpPost]
        public string DelteSampleLoginRelationById(string Id)
        {
            return SAMPLE.LoginRelation.DeleteLoginRelation(dbContext, Id);
        }

        [HttpPost]
        public string DelteSampleLoginTestById(string Id)
        {
            return SAMPLE.LoginRelation.DeleteLoginRelationTestDefinition(dbContext, Id);
        }

        [HttpPost]
        public string postDeleteSampleLogin(string Ids)
        {
            return SAMPLE.Sample.DeleteSampleLogin(dbContext, Ids).GetAwaiter().GetResult();
        }

        [HttpPost]
        public string AddSampleLoginTestDefinition(string SampleLoginId, string TestDefinitionId)
        {
            return SAMPLE.Sample.AddSampleLoginTestDefinition(dbContext, SampleLoginId, TestDefinitionId);
        }

        [HttpPost]
        public string AddSampleLoginSpecCollection(string SampleLoginId, string SpecCollectionId)
        {
            return SAMPLE.LoginRelation.AddSampleLoginSpecCollection(dbContext, SampleLoginId, SpecCollectionId);
        }

        [HttpPost]
        public string StartSampleLogin(string Ids)
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return SAMPLE.Sample.StartSampleLogin(dbContext, Ids, user.Id, user.FullName);
        }

        [HttpPost]
        public string UpdateSampleLoginIsRelease(string SampleLoginId, string IsRelease)
        {
            var login = SAMPLE.Sample.getSampleLogin(dbContext, SampleLoginId);
            login.IsRelease = IsRelease == "true" ? true : false;
            dbContext.Update(login);
            dbContext.SaveChanges();

            return "发布项更新成功！";
        }

        #endregion

        #region 样品运行时

        [Authorize(Roles = "Admin,分析员")]
        public ViewResult Sampling() => View("/Views/Sample/Runtime/Sampling.cshtml");

        [Authorize(Roles = "Admin,分析员")]
        public ViewResult ReceiveSamples() => View("/Views/Sample/Runtime/ReceiveSamples.cshtml");

        [Authorize(Roles = "Admin,分析员")]
        public ViewResult ResultEntry() => View("/Views/Sample/Runtime/ResultEntry.cshtml");

        [Authorize(Roles = "Admin,分析员,QA审核,经理审核")]
        public ViewResult ExamineAndVerify(string StepName)
        {
            ViewData["StepName"] = StepName;
            return View("/Views/Sample/Runtime/ExamineAndVerify.cshtml");
        }

        [Authorize(Roles = "Admin,样品管理")]
        public ViewResult SampleManager() => View("/Views/Sample/Runtime/SampleManager.cshtml");

        [HttpPost]
        public ViewResult SelectSamplingLab(string Ids, string LabType, string ModalID)
        {
            ViewData["Ids"] = Ids;
            ViewData["LabType"] = LabType;
            ViewData["ModalID"] = ModalID;
            return View("/Views/Sample/Runtime/SelectSamplingLab.cshtml");
        }

        [HttpPost]
        public JsonResult GetSamplingList(string limit, string offset)
        {
            var list = SAMPLE.Sample.getSamplingList(dbContext)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.Sample.getSamplingList(dbContext).Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public string Sampling(string Ids)
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return SAMPLE.Sample.Sampling(dbContext, Ids, user.Id, user.FullName);
        }

        [HttpPost]
        public string CreateSamplingLab(string Ids, string labName)
        {
            string file = null;
            if (labName.Contains("采样"))
                file = SAMPLE.Sample.CreateSamplingLab(dbContext, Ids, labName);
            else
                file = SAMPLE.Sample.CreateSampleLab(dbContext, Ids, labName);
            return file;
        }

        [HttpPost]
        public string SampleToExcel(string Ids)
        {
            var file = SAMPLE.Sample.SampleToExcel(dbContext, Ids);
            return file;
        }

        [HttpPost]
        public JsonResult GetLabList(string LabType)
        {
            var path = "";
            if (LabType == "Sampling")
                path = Common.getGlobalKeyValue(dbContext, "SamplingLab_Path");

            var files = Directory.GetFiles(path, "*.docx");
            var utl = new List<UseTypeList>();

            foreach (var item in files)
            {
                var name = item.Split('\\');
                utl.Add(new UseTypeList { Type = name[name.Length - 1], Use = false });
            }

            return Json(utl);
        }

        [HttpPost]
        public JsonResult GetReceiveSamples(string limit, string offset, string Ids)
        {
            var list = SAMPLE.Sample.getReceiveSamples(dbContext, Ids)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.Sample.getReceiveSamples(dbContext, Ids).Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public string ReceiveSamples(string Ids)
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return SAMPLE.Sample.ReceiveSamples(dbContext, Ids, user.Id, user.FullName);
        }

        [HttpPost]
        public JsonResult GetRestltBatchIdList()
        {
            var list = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                .Distinct(new SAMPLE.SampleBatchIdCompare())
                .Select(x => x.BatchId);

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetResultAnalyteList(string batchid)  // 获得待测分析项去重列表
        {
            var list = SAMPLE.Sample.getResultAnalyteByBatchid(dbContext, batchid)
                    .Distinct(new SAMPLE.ResultAnalyteCompare())
                    .OrderBy(x => x.AnalytesCode)
                    .Select(x => x.AnalytesCode);

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetTobeTestResultList(string batchid, string analytesCode, string limit, string offset)  // 获得待测分析项列表
        {
            var list = SAMPLE.Sample.getResultAnalyteByBatchid(dbContext, batchid)
                    .Where(s => s.AnalytesCode == analytesCode)
                    .OrderBy(x => x.SampleId).OrderBy(x => x.AnalytesCode)
                    .Select(x => new { x.Id, x.SampleId, x.TestName, x.TestTimes, x.AnalytesCode,x.Original, x.AlternativeResults, x.EqType })
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();

            var relist = from result in list
                         join sample in dbContext.Sample on result.SampleId equals sample.Id
                         select new
                         {
                             result.Id,
                             sample.SampleId,
                             sample.SampleNumber,
                             result.TestName,
                             result.TestTimes,
                             result.AnalytesCode,
                             result.Original,
                             result.AlternativeResults,
                             result.EqType,
                         };


            var res = new Common.PageHelper();
            res.total = SAMPLE.Sample.getResultAnalyteByBatchid(dbContext, batchid)
                    .Where(s => s.AnalytesCode == analytesCode).ToList().Count;
            res.rows = relist.OrderBy(s => s.SampleId).ToArray();

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetRestltBatchIdListByStepName(string StepName)
        {
            var list = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                .Distinct(new SAMPLE.SampleBatchIdCompare())
                .Select(x => x.BatchId);

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetRestltSamplesByBatchId(string limit, string offset, string BatchId)
        {
            var list = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                .Where(s => s.BatchId == BatchId)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.Sample.getResultEntrySamples(dbContext, null).Where(s => s.BatchId == BatchId).ToList().Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost] // 结果录入后续步骤根据批次号和步骤名称获得分析项列表
        public JsonResult GetRestltsByBatchIdAndStepName(string limit, string offset, string BatchId, string StepName)
        {
            
            var list = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                .Where(s => s.BatchId == BatchId)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName).Where(s => s.BatchId == BatchId).ToList().Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost] // 根据批次号和步骤名称获得所有分析项列表
        public JsonResult GetAllRestltsByBatchIdAndStepName(string limit, string offset, string BatchId, string StepName)
        {
            var slist = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName, BatchId).ToList();

            var rlist = from sample in slist
                        join result in dbContext.Result on sample.Id equals result.SampleId
                        orderby (sample.SampleId)
                        select new
                        {
                            result.Id,
                            sample.SampleId,
                            sample.SampleNumber,
                            result.TestName,
                            result.AnalytesCode,
                            result.AnalytesName,
                            result.LowA,
                            result.LowB,
                            result.StandardValue,
                            result.HighA,
                            result.HighB,
                            result.RoundingOff,
                            result.Units,
                            result.FUnits,
                            result.Original,
                            result.Final,
                            result.Conclusion,
                            result.RetestNo,
                            result.DetectionTimes,
                            result.TestTimes,
                            result.Status,
                            result.MethodId,
                            result.Assist,
                            result.Sort,
                            result.AlternativeResults,
                            result.EqUsageRecordId,
                            result.EqId,
                            result.EqType,
                            result.EntryModel,
                            result.EntryPersonName,
                            result.EntryTime,
                        };

            var res = new Common.PageHelper();
            res.total = rlist.Count();
            res.rows = rlist.Skip(int.Parse(offset)).Take(int.Parse(limit)).ToArray();

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetRestltSamples(string limit, string offset, string Type, string value)
        {
            SampleSample[] list = null;
            int total = 0;

            if (string.IsNullOrEmpty(value))
                return null;

            if (Type == "样品编号")
            {
                list = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                    .Where(s => s.SampleId.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                    .Where(s => value.Contains(s.SampleId)).ToList().Count;
            }
            if (Type == "名称")
            {
                list = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                    .Where(s => s.Name.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                    .Where(s => value.Contains(s.Name)).ToList().Count;
            }
            if (Type == "类型")
            {
                list = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                    .Where(s => s.Classification.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                    .Where(s => value.Contains(s.Classification)).ToList().Count;
            }
            if (Type == "分类")
            {
                list = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                    .Where(s => s.GenricClass.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getResultEntrySamples(dbContext, null)
                    .Where(s => value.Contains(s.GenricClass)).ToList().Count;
            }

            var res = new Common.PageHelper();
            res.total = total;
            res.rows = list;

            return Json(res);
        }

        [HttpPost] // 结果录入后续步骤根据查询类型和步骤名称获得分析项列表
        public JsonResult GetRestltsBySearchAndStepName(string limit, string offset, string Type, string value, string StepName)
        {
            SampleSample[] list = null;
            int total = 0;

            if (string.IsNullOrEmpty(value))
                return null;

            if (Type == "样品ID")
            {
                list = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.SampleId.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.SampleId.Contains(value)).ToList().Count;
            }
            if (Type == "样品编号")
            {
                list = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.SampleNumber.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.SampleNumber.Contains(value)).ToList().Count;
            }
            if (Type == "名称")
            {
                list = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.Name.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.Name.Contains(value)).ToList().Count;
            }
            if (Type == "类型")
            {
                list = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.Classification.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.Classification.Contains(value)).ToList().Count;
            }
            if (Type == "分类")
            {
                list = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.GenricClass.Contains(value))
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getSamplesByStepName(dbContext, StepName)
                    .Where(s => s.GenricClass.Contains(value)).ToList().Count;
            }

            var res = new Common.PageHelper();
            res.total = total;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetSampleResults(string Id)
        {
            var list = SAMPLE.Result.getSampleResults(dbContext, Id);
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetSampleBySearch(string limit, string offset, string Type, string value)
        {
            SampleSample[] list = null;
            int total = 0;

            if (Type == "批次号")
            {
                list = SAMPLE.Sample.getSampleList(dbContext)
                    .Where(s => s.BatchId == value)
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getSampleList(dbContext)
                    .Where(s => s.BatchId == value).ToList().Count;
            }
            if (Type == "样品ID")
            {
                list = SAMPLE.Sample.getSampleList(dbContext)
                    .Where(s => s.SampleId == value)
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getSampleList(dbContext)
                    .Where(s => s.SampleId == value).ToList().Count;
            }
            if (Type == "样品编号")
            {
                list = SAMPLE.Sample.getSampleList(dbContext)
                    .Where(s => s.SampleNumber == value)
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();
                total = SAMPLE.Sample.getSampleList(dbContext)
                    .Where(s => s.SampleNumber == value).ToList().Count;
            }

            var res = new Common.PageHelper();
            res.total = total;
            res.rows = list;

            return Json(res);
        }

        [HttpPost] // 手工录入结果
        public JsonResult ManualResult(string Id, string Original, string EqId=null)
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var result = SAMPLE.Result.ManualResult(dbContext, Id, Original, user.Id, user.FullName, out string except, EqId);

            if (!string.IsNullOrEmpty(except))
                return Json(except);

            if (string.IsNullOrEmpty(result.TestId)) // 不属于测试的分析项只返回一个值
            {
                List<SampleResult> relist = new List<SampleResult>();
                relist.Add(result);
                return Json(relist);
            }
            else
            {
                var relist = result.getSameTestResult(dbContext);
                return Json(relist);
            }
        }

        [HttpPost] // 自动登录默认结果
        public string DefaultResults(string Ids, string EqId)
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var idarry = Ids.Split(',');
            var list = SAMPLE.Result.getResultList(dbContext).Where(s => idarry.Contains(s.Id)).ToList();

            foreach (var item in list)
            {
                var result = SAMPLE.Result.ManualResult(dbContext, item.Id, item.Original, user.Id, user.FullName, out string except, EqId);
                if (!string.IsNullOrEmpty(except))
                    return except;
            }
            return "默认结果设置完成！";
        }

        [HttpPost]
        public ViewResult CallRecordSheet(string ResultId)
        {
            var result = SAMPLE.Result.getResult(dbContext, ResultId);
            var method = SAMPLE.Method.getMethod(dbContext, result.MethodId);

            ViewData["ResultId"] = ResultId;
            ViewData["SampleId"] = result.SampleId;
            // 如果电子记录单不存在了，此处应该连接到一个默认的页面，否者窗口打不开，也看不到任何错误。
            return View("/Views/Sample/RecordSheet/" + method.RecordSheet);
        }

        [HttpPost]
        public JsonResult GetTestAnalytes(string ResultId) // 记录单获得同一测试下所有分析项
        {
            var result = SAMPLE.Result.getResult(dbContext, ResultId);
            var list = result.getSameTestResult(dbContext);
            return Json(list);
        }

        [HttpPost]
        public string DoExamineAndVerify(string Ids) // 样品审核
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return SAMPLE.Sample.ExamineAndVerify(dbContext, Ids, user.Id, user.FullName).GetAwaiter().GetResult();
        }

        [HttpPost]
        public string Review(string ResultId) // 重测
        {
            var result = SAMPLE.Result.getResult(dbContext, ResultId);
            SAMPLE.Result.CreateReviewData(dbContext, result);

            var sample = SAMPLE.Sample.getSampleLogin(dbContext, result.SampleId);
            SAMPLE.TakeAStepBack(dbContext, sample);

            dbContext.SaveChanges();
            return "重测操作成功！," + sample.Id;
        }

        [HttpPost]
        public string DoAbandon(string SampleIds, string Suggestion) // 废弃指定样品
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return SAMPLE.Sample.DoAbandon(dbContext, SampleIds, user, Suggestion);
        }

        [HttpPost]
        public string UpdateResultAssist(string ResultId, string Assist) // 更新结果项报告过滤属性
        {
            
            bool assist = false;
            if (Assist == "true")
                assist = true;

            var st = SAMPLE.Result.UpdateAssist(dbContext, ResultId, assist);
            return st;
        }

        [HttpPost]
        public string UpdateResultFinalByFactor(string ResultId, string Factor, string Funits) // 根据转换因子更新分析项最终结果和最终结果单位
        {
            var st = SAMPLE.Result.UpdateResultFinalByFactor(dbContext, ResultId, Factor, Funits);
            return st;
        }

        [HttpPost]
        public string CreateSingleReport(string SampleId) // 生成单样品报告
        {
            var sample = SAMPLE.Sample.getSampleLogin(dbContext, SampleId);
            var st = SAMPLE.Sample.CreateSingleReport(dbContext, SampleId, sample.ReportName);
            return st;
        }

        [HttpPost]
        public string CreatMultiReport(string SampleBatchId, string ReportName) // 生成批量样品报告
        {
            var st = SAMPLE.Sample.CreatMultiReport(dbContext, SampleBatchId, ReportName);
            return st;
        }

        [HttpPost]
        public JsonResult GetSampleHistory(string SampleId) // 获取样品历史记录
        {
            var sample = SAMPLE.Sample.getSampleLogin(dbContext, SampleId);
            var list = WorkFlow.GetRuntimeWorkFlow(sample).RuntimeStepSequenceList
                        .Select(s => new
                        {
                            SampleId = sample.SampleId,
                            s.StepName,
                            s.Status,
                            s.RecordTime,
                            s.CurrentHandlerType,
                            s.CurrentHandlerId,
                            s.HandlingTime,
                            s.Suggestion
                        })
                        .ToArray();

            return Json(list.OrderBy(x => x.RecordTime));
        }

        [HttpPost]
        public JsonResult GetMenuItemCounter() // 获取菜单项计数器
        {
            var aSampleLogin = SAMPLE.Sample.getSampleLoginList(dbContext).Count;
            var aSampling = SAMPLE.Sample.getSamplingList(dbContext).Count;
            var aReceiveSamples = SAMPLE.Sample.getReceiveSamples(dbContext,null).Count;
            var aResultEntry = SAMPLE.Sample.getResultEntrySamples(dbContext, null).Count;
            var aExamineAndVerify = SAMPLE.Sample.getSamplesByStepName(dbContext, "同级审核").Count;
            var qaExamineAndVerify = SAMPLE.Sample.getSamplesByStepName(dbContext, "QA审核").Count;
            var maExamineAndVerify = SAMPLE.Sample.getSamplesByStepName(dbContext, "经理审核").Count;

            var CounterList = new { aSampleLogin = aSampleLogin > 0 ? aSampleLogin.ToString():null,
                aSampling = aSampling > 0 ? aSampling.ToString() : null,
                aReceiveSamples = aReceiveSamples > 0 ? aReceiveSamples.ToString() : null,
                aResultEntry = aResultEntry > 0 ? aResultEntry.ToString() : null,
                aExamineAndVerify = aExamineAndVerify > 0 ? aExamineAndVerify.ToString() : null,
                qaExamineAndVerify = qaExamineAndVerify > 0 ? qaExamineAndVerify.ToString() : null,
                maExamineAndVerify = maExamineAndVerify > 0 ? maExamineAndVerify.ToString() : null,
            };

            return Json(CounterList);
        }

        [HttpPost]
        public string InitializeAnalysis(string ResultId) // 初始化指定分析项
        {
            return SAMPLE.Result.InitializeAnalysis(dbContext, ResultId);
        }

        [HttpPost]
        public string UpdateSamplingPoint(string SampleId, string SamplingPoint) // 更新样品采样点信息
        {
            var sample = SAMPLE.Sample.getSampleLogin(dbContext, SampleId);
            sample.SamplingPoint = SamplingPoint;
            dbContext.Update(sample);
            dbContext.SaveChanges();
            return "采样点更新成功！";
        }

        #endregion

        #region 留样管理

        [Authorize(Roles = "Admin,留样管理")]
        public ViewResult RetentionSampleManage() => View("/Views/Sample/RetentionSampleManage.cshtml");

        public ViewResult AddRetentionUse(string RetentionSampleIds, string ModalID)
        {
            ViewData["RetentionSampleIds"] = RetentionSampleIds;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        public ViewResult DisRetentionSample(string RetentionSampleIds, string ModalID)
        {
            ViewData["RetentionSampleIds"] = RetentionSampleIds;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetRetentionSampleById(string RetentionSampleId)
        {
            var rs = SAMPLE.RetentionSample.getRetentionSample(dbContext, RetentionSampleId);
            return Json(rs);
        }

        [HttpPost]
        public JsonResult GetRetentionSample(string batchId, string limit, string offset)// 返回等待被接收的留样
        {
            if (batchId.IsNullOrEmpty())
            {
                var list = SAMPLE.RetentionSample.getRegistrationList(dbContext)
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();

                var res = new Common.PageHelper();
                res.total = SAMPLE.RetentionSample.getRegistrationList(dbContext).ToList().Count;
                res.rows = list;

                return Json(res);
            }
            else
            {
                var list = SAMPLE.RetentionSample.getRegistrationList(dbContext)
                    .Where(s => s.BatchId == batchId)
                    .Skip(int.Parse(offset)).Take(int.Parse(limit))
                    .ToArray();

                var res = new Common.PageHelper();
                res.total = SAMPLE.RetentionSample.getRegistrationList(dbContext).Where(s => s.BatchId == batchId).ToList().Count;
                res.rows = list;

                return Json(res);
            }
        }

        [HttpPost]
        public JsonResult GetRetentionSampleBatch()// 返回等待被接收的留样的批次号
        {
            var list = SAMPLE.RetentionSample.getRegistrationList(dbContext)
                .Distinct(new SAMPLE.RetentionSampleBatchIdCompare())
                .Select(s => new { s.BatchId });
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetDisposeSample(string batchId, string limit, string offset)// 返回等待被处置的留样
        {
            if (batchId.IsNullOrEmpty())
            {
                var list = SAMPLE.RetentionSample.getRecipientList(dbContext)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

                var res = new Common.PageHelper();
                res.total = SAMPLE.RetentionSample.getRecipientList(dbContext).ToList().Count;
                res.rows = list;

                return Json(res);
            }
            else
            {
                var list = SAMPLE.RetentionSample.getRecipientList(dbContext)
                .Where(s => s.BatchId == batchId)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

                var res = new Common.PageHelper();
                res.total = SAMPLE.RetentionSample.getRecipientList(dbContext).Where(s => s.BatchId == batchId).ToList().Count;
                res.rows = list;

                return Json(res);
            }
        }

        [HttpPost]
        public JsonResult GetDisposeSampleBatch() // 返回等待被处置的留样的批次号
        {
            var list = SAMPLE.RetentionSample.getRecipientList(dbContext)
                .Distinct(new SAMPLE.RetentionSampleBatchIdCompare())
                .Select(s => new { s.BatchId });
            return Json(list);
        }

        [HttpPost]
        public string RecipientSample(string Ids, string Note, string jsonRetentionConfig, string KeepTo)// 接收留样
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var st = SAMPLE.RetentionSample.Recipient(dbContext, Ids, user.Id, user.FullName, Note, jsonRetentionConfig, KeepTo).GetAwaiter().GetResult();
            return st;
        }

        [HttpPost]
        public string DisposalSample(string Ids, string DisposalInstructions, string StarWFParameters)// 处置留样
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var st = SAMPLE.RetentionSample.Disposal(dbContext, Ids, user.Id, user.FullName, DisposalInstructions);

            if (st.Contains("成功") && StarWFParameters != null) // 如果前台传过来启动流程的参数，说明处置需要走审批流程。
            {
                StarWFParameters swfp = JsonConvert.DeserializeObject<StarWFParameters>(StarWFParameters);
                var wfc = new WorkFlowController(dbContext);
                return wfc.Start(swfp.WorkFlowId, swfp.DomainName, Ids.Split(',')[0], swfp.ApprovedByID, swfp.ApprovedByName, user, CreatRemindDis);
            }
            return st;
        }

        [HttpPost]
        public string UpdateRetentionDisApproval(string RetentionSampleId) // 更新留样中的处置审批
        {
            var rs = SAMPLE.RetentionSample.getRetentionSample(dbContext, RetentionSampleId);
            if (rs.DisApproval)
                rs.DisApproval = false;
            else 
                rs.DisApproval = true;
            dbContext.Update (rs);
            dbContext.SaveChanges();
            return "更新成功！";
        }

        [HttpPost]
        public string UpdateRetentionUseApproval(string RetentionSampleId) // 更新留样中的领用审批
        {
            var rs = SAMPLE.RetentionSample.getRetentionSample(dbContext, RetentionSampleId);
            if (rs.UseApproval)
                rs.UseApproval = false;
            else
                rs.UseApproval = true;
            dbContext.Update(rs);
            dbContext.SaveChanges();
            return "更新成功！";
        }

        [HttpPost]
        public string postAddRetentionUse(string RetentionSampleIds, string ContainerNumber, string Quantity, string Note, string StarWFParameters) // 添加留样领用记录,支持批量领用
        {
            if (!int.TryParse(ContainerNumber, out int a))
                return "ContainerNumber：不能转换为整数！";
            if (!decimal.TryParse(Quantity, out decimal b))
                return "ContainerNumber：不能转换为有效数字！";

            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var ru = SAMPLE.RetentionSample.AddRetentionUse(dbContext, RetentionSampleIds, a, b, Note,user.Id,user.FullName, out string st);

            if (st.Contains("成功") && StarWFParameters != null) // 如果前台传过来启动流程的参数，说明该出库单需要走审批流程。
            {
                StarWFParameters swfp = JsonConvert.DeserializeObject<StarWFParameters>(StarWFParameters);
                var wfc = new WorkFlowController(dbContext);
                return wfc.Start(swfp.WorkFlowId, swfp.DomainName, ru.Id, swfp.ApprovedByID, swfp.ApprovedByName, user, CreatRemindUse);
            }
            return st;
        }

        /// <summary>
        /// 留样领用发起流程，并生成通知消息
        /// </summary>
        /// <param name="DomainId"></param>
        /// <param name="ApprovedByID"></param>
        /// <param name="ApprovedByName"></param>
        /// <param name="workFlow"></param>
        /// <param name="user"></param>
        private string CreatRemindUse(string DomainId, string ApprovedByID, string ApprovedByName, WorkFlow workFlow, CommonUser user)
        {
            var domain = SAMPLE.RetentionSample.getRetentionUse(dbContext, DomainId);
            var ru = SAMPLE.RetentionSample.getRetentionSample(dbContext, domain.RetentionSampleId);
            workFlow.CreateRuntimeWorkFlow(domain);
            workFlow.RunWorkFlow(handlerType: user.FullName, handlerId: user.Id); // 自动发起
            workFlow.RunWorkFlow(additionalType: WorkFlow.AdditionalType.下一步处理人.ToString(), additionalData: ApprovedByID); //自动完成发起步骤

            var remind = new Remind();
            remind.Title = "留样领用审批";
            remind.Content = user.FullName + " 发起的留样领用需要您审批！\n" +
                " 批次号：" + ru.BatchId + "\n" +
                " 样品ID：" + domain.SampleId;
            remind.WorkFlowId = workFlow.RuntimeWorkFlow.Id; // 只有在流程发起时，才记录流程ID，这样方便以后查询提醒标题和内容
            remind.UserId = ApprovedByID;
            remind.UserName = ApprovedByName;
            remind.SendRemindId = user.Id;
            remind.SendRemindName = user.FullName;
            dbContext.Remind.Add(remind);
            dbContext.SaveChanges();
            return "留样领用审批流程发起成功！";
        }

        /// <summary>
        /// 留样处置发起流程，并生成通知消息
        /// </summary>
        /// <param name="DomainId"></param>
        /// <param name="ApprovedByID"></param>
        /// <param name="ApprovedByName"></param>
        /// <param name="workFlow"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private string CreatRemindDis(string DomainId, string ApprovedByID, string ApprovedByName, WorkFlow workFlow, CommonUser user)
        {
            var domain = SAMPLE.RetentionSample.getRetentionSample(dbContext, DomainId);
            workFlow.CreateRuntimeWorkFlow(domain);
            workFlow.RunWorkFlow(handlerType: user.FullName, handlerId: user.Id); // 自动发起
            workFlow.RunWorkFlow(additionalType: WorkFlow.AdditionalType.下一步处理人.ToString(), additionalData: ApprovedByID); //自动完成发起步骤

            var remind = new Remind();
            remind.Title = "留样处置审批";
            remind.Content = user.FullName + " 发起的留样处置需要您审批！\n" +
                " 样品ID：" + domain.SampleId + "\n" + 
                " 处置说明：" + domain.DisposalInstructions;

            remind.WorkFlowId = workFlow.RuntimeWorkFlow.Id; // 只有在流程发起时，才记录流程ID，这样方便以后查询提醒标题和内容
            remind.UserId = ApprovedByID;
            remind.UserName = ApprovedByName;
            remind.SendRemindId = user.Id;
            remind.SendRemindName = user.FullName;
            dbContext.Remind.Add(remind);
            dbContext.SaveChanges();
            return "留样处置审批流程发起成功！";
        }

        [HttpPost]
        public JsonResult GetRetentionUses(string RetentionSampleId)// 返回留样领用记录
        {
            var list = dbContext.RetentionUse.Where(s => s.RetentionSampleId == RetentionSampleId)
                .OrderBy(s => s.UseDateTime)
                .ToList();
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetRetentionUseApprovalRecords(string RetentionUseId) // 获取留样领用审批记录
        {
            var rsample = SAMPLE.RetentionSample.getRetentionUse(dbContext, RetentionUseId);
            var list = WorkFlow.GetRuntimeWorkFlow("RetentionUse", rsample.Id);
            if (list == null)
                return null;
            else
                return Json(list.RuntimeStepSequenceList.ToArray().OrderBy(x => x.RecordTime));
        }

        #endregion

        #region 留样配置

        [Authorize(Roles = "Admin,样品定义")]
        public ViewResult RetentionConfig() => View();

        [HttpPost]
        public ViewResult AddRetentionConfig(string Id, string ModalID)
        {
            ViewData["RetentionConfigId"] = Id;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetRetentionConfigList(string limit, string offset)
        {
            var list = SAMPLE.RetentionConfig.getRetentionConfigList(dbContext)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = SAMPLE.RetentionConfig.getRetentionConfigList(dbContext).Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetRetentionConfig(string Id)
        {
            var rc = SAMPLE.RetentionConfig.getRetentionConfig(dbContext, Id);
            return Json(rc);
        }

        [HttpPost]
        public JsonResult GetRetentionConfigName()
        {
            var list = SAMPLE.RetentionConfig.getRetentionConfigList(dbContext)
                .Select(s => new { s.Id, s.Name });

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetRetentionConfigContainer()
        {
            var list = SAMPLE.RetentionConfig.getRetentionConfigList(dbContext)
                .Distinct(new SAMPLE.RetentionConfigContainerCompare())
                .Select(s => new { s.Container });

            return Json(list);
        }

        [HttpPost]
        public JsonResult GetRetentionConfigUnit()
        {
            var list = SAMPLE.RetentionConfig.getRetentionConfigList(dbContext)
                .Distinct(new SAMPLE.RetentionConfigUnitCompare())
                .Select(s => new { s.Unit });

            return Json(list);
        }

        [HttpPost]
        public string postAddRetentionConfig(string jsonStr)
        {
            RetentionConfig retention = JsonConvert.DeserializeObject<RetentionConfig>(jsonStr);  //反序列化，字符串转换为类
            var st = retention.Add(dbContext);
            return st;
        }

        [HttpPost]
        public string UpdateRetentionConfig(string jsonStr)
        {
            RetentionConfig retention = JsonConvert.DeserializeObject<RetentionConfig>(jsonStr);  //反序列化，字符串转换为类
            var st = retention.Update(dbContext);
            return st;
        }

        [HttpPost]
        public string DelRetentionConfig(string Id)
        {
            return SAMPLE.RetentionConfig.Delete(dbContext, Id);
        }
        
        [HttpPost]
        public string UpdateRetentionCfDisApproval(string RetentionConfigId) // 更新留样配置中的处置审批
        {
            var rs = SAMPLE.RetentionConfig.getRetentionConfig(dbContext, RetentionConfigId);
            if (rs.DisApproval)
                rs.DisApproval = false;
            else
                rs.DisApproval = true;
            dbContext.Update(rs);
            dbContext.SaveChanges();
            return "更新成功！";
        }

        [HttpPost]
        public string UpdateRetentionCfUseApproval(string RetentionConfigId) // 更新留样配置中的领用审批
        {
            var rs = SAMPLE.RetentionConfig.getRetentionConfig(dbContext, RetentionConfigId);
            if (rs.UseApproval)
                rs.UseApproval = false;
            else
                rs.UseApproval = true;
            dbContext.Update(rs);
            dbContext.SaveChanges();
            return "更新成功！";
        }

        #endregion
    }
}
